package com.srcbox.file.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.srcbox.file.R
import com.srcbox.file.adapter.MainPager
import com.srcbox.file.data.AppSetting
import com.srcbox.file.data.ScreenCaptureInfo
import com.srcbox.file.data.Search
import com.srcbox.file.fragment.pager.MainA
import com.srcbox.file.fragment.pager.MainB
import com.srcbox.file.fragment.pager.MainC
import com.srcbox.file.util.*
import com.yang.easyhttp.EasyHttpClient
import com.yang.easyhttp.callback.EasyJsonCallback
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.io.File
import kotlin.system.exitProcess


class Main : AppCompatActivity() {


    private var exitTime = 0L
    private var eggDialog: EggDialog? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        GlobalMethods(this).initActivityUi()

        /*val statusBarPar = statusBarS.layoutParams
        statusBarPar.height = EggUtil.getStatusBarHeight(this)
        statusBarS.layoutParams = statusBarPar
        EggUtil.transparency(this)
*/
        eggDialog = EggDialog(this@Main)

        EggUtil.loadIcon(this, icon_nav_one, AppSetting.FONT_COLOR)
        EggUtil.loadIcon(this, icon_nav_three, AppSetting.FONT_COLOR)
        EggUtil.loadIcon(this, main_sidle, AppSetting.FONT_COLOR)
        init()
        initUi()
        initUiEvent()
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            if (!Search.isSearch) {
                if ((System.currentTimeMillis() - exitTime) < 2000) {
                    exitProcess(0)
                } else {
                    EggUtil.toast(this, "再按一次退出应用")
                    exitTime = System.currentTimeMillis()
                }
            } else {
                Search.search(this, Search.v!!, Search.packList, "")
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun requestPermissions() {
        XXPermissions.with(this).permission(Permission.Group.STORAGE)
            .request(object : OnPermission {
                override fun noPermission(denied: MutableList<String>?, quick: Boolean) {
                    if (quick) {
                        XXPermissions.gotoPermissionSettings(this@Main)
                    } else {
                        EggUtil.toast(this@Main, "权限申请失败")
                    }
                }

                override fun hasPermission(granted: MutableList<String>?, all: Boolean) {}
            })
    }

    private fun init() {
        val isProtoPath = "${filesDir.path}/isProto.txt"
        val isProto = File(isProtoPath)
        if (!isProto.exists()) {
            ProtocolDialog(this, isProto) {
                if (it) {
                    requestPermissions()
                } else {
                    exitProcess(0)
                }
            }.create()
        } else {
            requestPermissions()
            initHttp()
        }

        var front = ""
        val jsonO = EggUtil.readSetting(this)
        if (jsonO["file_storage_path"] == "山盒/") {
            front = AppSetting.localStoragePath
        }

        AppSetting.fileStoragePath =
            front + jsonO["file_storage_path"].toString()


        AppSetting.extTablePath = filesDir.path + "/ext1.5.json"
        if (!File(AppSetting.extTablePath).exists()) {
            EggIO().assetsFileToSdPath(this, "ext1.5.json", AppSetting.extTablePath)
        }
    }

    private fun initHttp() {

        EasyHttpClient.get(AppSetting.APP_CONTENT_LINK, object : EasyJsonCallback() {
            override fun onSuccess(content: JSONObject) {
                try {
                    val currAppVersion =
                        this@Main.applicationContext.packageManager.getPackageInfo(
                            this@Main.packageName,
                            0
                        ).versionCode

//                EggUtil.toast(this@MainActivity, )
                    val version = content["version_code"].toString()
                    if (version.toFloat() > currAppVersion) {

                        eggDialog!!.create(EggDialog.UPDATE_DIALOG)
                            .setContent(content["update_content"].toString())
                            .setTitle("有新版本啦！")
                            .setNewVer(
                                content["version_name"].toString(),
                                content["version_code"].toString(),
                                content["update_url"].toString()
                            )

                    } else {
                        if (!EggDialog.isUse) {
                            println("aaaa")
//                            EggUtil.toast(this@Main,"aaa")
                            if (!EggUtil.readSetting(this@Main).getBoolean("g_is_cancel")) {
                                eggDialog!!.create(EggDialog.DAY_DIALOG)
                                    .hideVer().setTitle("每日公告")
                                    .setContent(content["content"].toString())
                            }
                        }
                    }
                } catch (e: Exception) {
                    println(e.message)
                }
            }

            override fun onFailure(error: Throwable?, content: String?) {
                EggUtil.toast(this@Main, "出现错误：$content\n$error")
            }
        })
    }

    private fun initUiEvent() {
        nav_one.setOnClickListener {
            main_pager.currentItem = 0

        }



        nav_two.setOnClickListener {
            main_pager.currentItem = 1
        }

        nav_three.setOnClickListener {
            main_pager.currentItem = 2
        }
        initUiListener()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (!Settings.canDrawOverlays(this)) {
                EggUtil.toast(this, "您没有授予权限哦")
                return
            }
            EggUtil.toast(this, "bbbb")
            FloatWin.Data.floatWin?.show()
            return
        }

        if (requestCode == ScreenCaptureInfo.CODE && data != null) {
            if (!ScreenCaptureInfo.isStart){
                FloatWin(this).show()
            }
            ScreenCaptureInfo.intentData = data
            ScreenCaptureInfo.resultCode = resultCode
            val intent = Intent(this, ScreenCaptureUtil::class.java)
            if (Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
        } else {
            EggUtil.toast(this, "您没有授予权限哦")
        }
    }


    @SuppressLint("InflateParams")
    private fun initUi() {

        alterNavStyle(0)

        val fArr = ArrayList<Fragment>()
        fArr.add(MainA())
        fArr.add(MainB())
        fArr.add(MainC())
        main_pager.adapter = MainPager(supportFragmentManager, fArr)
        main_pager.currentItem = 0
    }


    private fun alterNavStyle(point: Int) {
        when (point) {
            0 -> {
                icon_nav_one.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
                icon_nav_three.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
            }
            2 -> {
                icon_nav_one.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
                icon_nav_three.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
            }
            1 -> {
                icon_nav_one.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
                icon_nav_three.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
            }
        }
    }

    private fun initUiListener() {
        main_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                alterNavStyle(position)
            }
        })
    }

    object Data {
        var isALoad = false
    }
}


/*val setFPath = filesDir.path + "/setting1.1.json"
var front = ""
if (!File(setFPath).exists()) {
    EggIO().assetsFileToSdPath(this, "setting1.1.json", setFPath)
}
val jsonO = JSON.parseObject(EggIO().readFile(setFPath))
*/


/*NotificationDialog(
       this@Main,
       NotificationDialog.APP_UPDATE
   ).ball(
       content["update_content"].toString(),
       content["update_url"].toString(),
       version.toFloat()
   )*/
/*   NotificationDialog(
                  this@Main,
                  NotificationDialog.DAY_CONTENT
              ).ball(content["content"].toString(), appVersion = version.toFloat())*/

//        findViewById<FrameLayout>(R.id.fragmentLay).background;
//        tabLay.setTabData(arrayOf("应用", "本地"), this, R.id.fragmentLay, fragments)

//Page 1 代码
/*
val capImgB = onePager.findViewById<Button>(R.id.nav_one_b1)
capImgB.setOnClickListener {


}

val appListRoot = onePager.findViewById<CardView>(R.id.app_ist_root)
val appSearchEdit = onePager.findViewById<AppCompatEditText>(R.id.app_search_edit)
val grad = GradientDrawable()
val radii = FloatArray(8)
radii[0] = 160f
radii[1] = 160f
radii[2] = 160f
radii[3] = 160f
radii[4] = 0f
radii[5] = 0f
radii[6] = 0f
radii[7] = 0f
grad.cornerRadii = radii
grad.setStroke(1, Color.parseColor("#ffffff"))
grad.setColor(Color.parseColor("#ffffff"))
appListRoot.background = grad
appListRoot.cardElevation = 1f

val grad2 = GradientDrawable()
grad2.cornerRadii = radii
grad2.setColor(Color.parseColor("#eeeeee"))
appSearchEdit.background = grad2

val buttonV = onePager.findViewById<Button>(R.id.nav_one_b1)
val appListV =
    onePager.findViewById<RecyclerView>(R.id.app_ist)
val listLoader = onePager.findViewById<LottieAnimationView>(R.id.listLottie)
//        val searchApp = onePager.findViewById<LinearLayout>(R.id.search_app)

EggUtil.setViewRadius(buttonV, AppSetting.STRESS_COLOR, 1, AppSetting.STRESS_COLOR, 20f)
val packList = this.packageManager.getInstalledPackages(0)
appListV.layoutManager = GridLayoutManager(this, 2)
appListV.adapter = AppList(this, packList)


appSearchEdit.setOnEditorActionListener { t, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
        listLoader.visibility = View.VISIBLE
        appListV.visibility = View.GONE
        Thread {
            var newPackageList: ArrayList<PackageInfo>? = ArrayList<PackageInfo>()
            packList.forEach {
                if (it.applicationInfo.loadLabel(this.packageManager).contains(
                        t.text,
                        true
                    )
                ) {
                    newPackageList?.add(it)
                }
            }
            runOnUiThread {
                appListV.adapter = AppList(this, newPackageList!!)
                listLoader.visibility = View.GONE
                appListV.visibility = View.VISIBLE
                newPackageList = null
                listLoader.cancelAnimation()
                EggUtil.hideKeyboard(this)
                System.gc()
            }
        }.start()
    }
    true
}
*/

//        val tabLay = onePager.findViewById<TableLayout>(R.id.tab_lay)
//        tabLay.addT
//Page 2 代码


//Page 3 代码


//        icon_nav_two.setImageBitmap(BitmapFactory.decodeStream(assets.open("img/moun.png")))
/* val viewList = ArrayList<View>()
 val navOneV = layoutInflater.inflate(R.layout.main_nav_one, null, false)
 val navTwoV = layoutInflater.inflate(R.layout.main_nav_two, null, false)
 val navThreeV = layoutInflater.inflate(R.layout.main_nav_three, null, false)
 viewList.add(navOneV)
 viewList.add(navTwoV)
 viewList.add(navThreeV)
 main_pager.adapter = MainPager(viewList)*/
//        initPagerUi(navOneV, navTwoV, navThreeV)

/* if (!ScreenCaptureInfo.isStart) {
                 if (!initAccessibilityPermissions()) {
                     return@setOnClickListener
                 }

                 ScreenCaptureUtil.readyCapture(this, ScreenCaptureInfo.CODE)
                 ScreenCaptureInfo.isStart = true

                 EasyFloat.with(this).setLayout(R.layout.float_win)
                     .setShowPattern(ShowPattern.ALL_TIME)
                     .setDragEnable(true).setSidePattern(SidePattern.DEFAULT)
                     .setTag("one")
                     .registerCallback {
                         createResult { _, _, view ->
                             val rootImg = view?.findViewById<LottieAnimationView>(R.id.root_img)
                             view?.setOnLongClickListener {

                                 ScreenCaptureInfo.isStart = false
                                 rootImg?.visibility = View.GONE
                                 EggUtil.toast(this@MainActivity, "已关闭")
                                 true
                             }

                             view?.setOnClickListener {
                                 rootImg?.visibility = View.GONE
                                 if (ScreenCaptureInfo.screenCaptureUtilInterface != null) {
                                     ScreenCaptureInfo.screenCaptureUtilInterface?.startCapture(
                                         this@Main,
                                         ScreenCaptureInfo.resultCode,
                                         ScreenCaptureInfo.intentData!!
                                     ) {
                                         ScreenCaptureUtil.getScreenImage(
                                             this@Main,
                                             it,
                                             rootImg!!
                                         )
                                     }
                                 } else {
                                     EggUtil.toast(this@Main, "出现了一点问题")
                                 }
                             }
                         }
                     }
                     .show()
             } else {
                 EasyFloat.dismiss(this, "one")
                 EggUtil.toast(this@Main, "已关闭")
                 ScreenCaptureInfo.isStart = false
             }*/

/*

 var newAppList: ArrayList<AppInfo>? = null
                newAppList = ArrayList()
                appInfoList?.forEach {
                    if (it.name!!.contains(t.text, true)) {
                        newAppList.add(it)
                    }
                }
                if (newAppList.isEmpty()) {
                    EggUtil.toast(this, "没有此应用")
                } else {
                    appListV.adapter = AppList(newAppList, this)
                    EggUtil.hideKeyboard(this)
                }

        Thread {
            appInfoList = ArrayList<AppInfo>()
            this.packageManager.getInstalledPackages(0).forEach {
                val appInfo = AppInfo(
                    it.applicationInfo.loadLabel(this.packageManager).toString(),
                    it.versionName,
                    it.applicationInfo.sourceDir,
                    it.applicationInfo.loadIcon(this.packageManager),
                    it.packageName
                )
                appInfoList?.add(appInfo)
            }

            runOnUiThread {
                appListV.visibility = View.VISIBLE
                appListV.layoutManager = GridLayoutManager(this, 2)
                appListV.adapter = AppList(appInfoList, this)
                listLoader.visibility = View.GONE
                searchApp.visibility = View.VISIBLE
                listLoader.cancelAnimation()
            }
        }.start()


//        val listLoader = onePager.findViewById<LottieAnimationView>(R.id.list_loader)

                icon_nav_one.textSize = EggUtil.sp2px(this, 10F).toFloat()



               icon_nav_one.textSize = EggUtil.sp2px(this, 5F).toFloat()


        val oneList = onePager.findViewById<RecyclerView>(R.id.one_list)
        packageList.add("com.wuba")
        packageList.add("org.autojs.autojs")
        packageList.add("com.alibaba.aliyun")
        oneList.layoutManager = GridLayoutManager(this, 3)
        oneList.adapter = MainOneList(packageList, this)

//        GlobalMethods(this).initActivityUi()
        /* val systemBarTintManager = SystemBarTintManager(this)

         EggUtil.setTranslucentStatus(this, true)
         systemBarTintManager.isStatusBarTintEnabled = true
         systemBarTintManager.setNavigationBarTintEnabled(true)
         systemBarTintManager.setTintColor(Color.parseColor("#2196f3"))
 */
/*          .initIcon(icon_nav_one, icon_nav_three, main_sidle)*/


//                nav_one_text.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
//                icon_nav_two.textSize = EggUtil.sp2px(this, 5F).toFloat()
//                icon_nav_two.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                nav_two_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                icon_nav_three.textSize = EggUtil.sp2px(this, 5F).toFloat()


//                nav_three_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                nav_one_text.visibility = View.VISIBLE
//                nav_two_text.visibility = View.GONE
//                nav_three_text.visibility = View.GONE

//                icon_nav_one.textSize = EggUtil.sp2px(this, 5F).toFloat()

//                nav_one_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                icon_nav_two.textSize = EggUtil.sp2px(this, 10F).toFloat()
//                icon_nav_two.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
//                nav_two_text.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
//                icon_nav_three.textSize = EggUtil.sp2px(this, 5F).toFloat()

//                nav_three_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                nav_one_text.visibility = View.GONE
//                nav_two_text.visibility = View.VISIBLE
//                nav_three_text.visibility = View.GONE

//                nav_one_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                icon_nav_two.textSize = EggUtil.sp2px(this, 5F).toFloat()
//                icon_nav_two.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                nav_two_text.setTextColor(Color.parseColor(AppSetting.TAB_NO_FOCUS_COLOR))
//                icon_nav_three.textSize = EggUtil.sp2px(this, 10F).toFloat()

//                nav_three_text.setTextColor(Color.parseColor(AppSetting.STRESS_COLOR))
//                nav_one_text.visibility = View.GONE
//                nav_two_text.visibility = View.GONE
//                nav_three_text.visibility = View.VISIBLE

        iconOneT2.setOnClickListener {
            it as TextView
            val rotateAnim = RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f)
            rotateAnim.duration = 3000
            it.animation = rotateAnim
            rotateAnim.start()

            oneList.visibility = View.VISIBLE
            val translateAnimation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.ABSOLUTE,
                0f,
                Animation.RELATIVE_TO_SELF,
                -50f,
                Animation.ABSOLUTE,
                0f
            )
            translateAnimation.duration = 2000
            oneList.animation = translateAnimation
            translateAnimation.start()

        }


val r = RoundRectShape(null, null, null)
val rectF = RectF(100f, 0f, 0f, 0f)
val roundRectShape = RoundRectShape(null, rectF, null)
val shapeDrawable = ShapeDrawable(roundRectShape)
shapeDrawable.paint.isAntiAlias = true
shapeDrawable.paint.style = Paint.Style.STROKE
shapeDrawable.paint.strokeWidth = 10f
shapeDrawable.paint.color = Color.parseColor(AppSetting.STRESS_COLOR)*/

//        val layerDrawable = LayerDrawable(arrayOf(shapeDrawable))
//onePager.findViewById<TextView>(R.id.lately_text).background = shapeDrawable

//        val appList: List<PackageInfo> = activity.packageManager.getInstalledPackages(0)
//        initList(appList)
/* private fun initList(data: List<PackageInfo>) {
     val layoutManager = LinearLayoutManager(this)
     //layoutManager.setMeasuredDimension(RecyclerView.LayoutParams.MATCH_PARENT,RecyclerView.LayoutParams.WRAP_CONTENT)
     list_app.layoutManager = layoutManager
     list_app.adapter = AppList(data, this)
 }*/